package com.live.task;

import java.io.InputStream;
import java.io.StringWriter;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlSerializer;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.Window;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.live.activity.R;
import com.live.common.Constant;
import com.live.tools.LiveTools;

public class LiveScore extends AsyncTask<Bundle, Integer, String> {

	private List<Map<String, Object>> liveScoreList = null;

	private ListView scoreList;

	private ProgressDialog proDialog = null;

	private Context context = null;

	public boolean refresh = true;

	private String matchId = null;

	private String matchOptaId = null;

	private TextView homeTeamScore = null;

	private TextView visitTeamScore = null;

	private TextView matchStatus = null;

	public LiveScore(Context context, ListView scoreList, TextView homeTeamScore, TextView visitTeamScore,
			TextView matchStatus, boolean refresh) {
		this.context = context;
		this.refresh = refresh;
		this.scoreList = scoreList;
		this.matchStatus = matchStatus;
		this.homeTeamScore = homeTeamScore;
		this.visitTeamScore = visitTeamScore;
	}

	// 此方法在主线程执行,当任务执行之前开始调用此方法，可以在这里显示进度对话框
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		if (refresh) {
			Log.i("PageTask", "onPreExecute()  " + Thread.currentThread().getId());
			proDialog = new ProgressDialog(context);
			proDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			proDialog.setMessage("数据加载中，请稍候。");
			proDialog.show();
		}
	}

	// 此方法在后台线程执行，完成任务的主要工作，通常需要较长的时间。
	// 在执行过程中可以调用publicProgress(Progress...)来更新任务的进度。

	@Override
	protected String doInBackground(Bundle... params) {
		Log.i("PageTask", "doInBackground... " + Thread.currentThread().getId());

		matchId = params[0].getString("matchId");
		matchOptaId = params[0].getString("matchOptaId");

		String url = Constant.SITE_URL + "live_score.php?";
		url += "matchId=" + matchId + "&matchOptaId=" + matchOptaId;

		// 取得本机MAC地址
		String mac = LiveTools.getLocalMacAddress(context);
		if (mac == null) {
			mac = "android";
		}
		// 此URL记录观看比赛者
		SharedPreferences store = context.getSharedPreferences(Constant.PREFS_NAME, 0);
		url += "&id=" + store.getString("id", null) + "&mac=" + mac;

		// 第一次进入到比分详细画面，刷新不算
		if (refresh) {
			url += "&r=1";
		} else {
			url += "&r=0";
		}

		// 读取本机缓存数据
		liveScoreList = LiveTools.readFile(context, matchId + ".xml".toString());

		if (liveScoreList.size() > 0) {

			// 如果缓存内有数据
			Map<String, Object> score = liveScoreList.get(0);
			String scoreId = (String) score.get("scoreId");
			url += "&scoreId=" + scoreId;

			List<Map<String, Object>> liveScoreListTemp = getMatchDetail(url);
			// 如果有更新数据，则更新比分列表
			if (liveScoreListTemp.size() > 0) {
				liveScoreList.addAll(0, liveScoreListTemp);
			}
		} else {
			// 如果缓存内没有数据
			liveScoreList = getMatchDetail(url);
		}

		publishProgress();
		return null;
	}

	// 此方法在主线程执行，用于显示任务执行的进度
	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		Log.i("PageTask", "onProgressUpdate()  " + Thread.currentThread().getId());

		// 当存在直播数据的时候
		if (liveScoreList.size() > 0) {

			SimpleAdapter adapter = new SimpleAdapter(context, liveScoreList, R.layout.score_list, new String[] {
					"scoreTime", "homeTeamScore", "visitTeamScore", "scoreAction" }, new int[] { R.id.scoreTime,
					R.id.homeTeamScore, R.id.visitTeamScore, R.id.scoreAction });

			scoreList.setAdapter(adapter);

			Map<String, Object> score = liveScoreList.get(0);

			// 更新比分
			homeTeamScore.setText((String) score.get("homeTeamScore"));
			visitTeamScore.setText((String) score.get("visitTeamScore"));

			// 更新状态
			if ("未开始".equals(matchStatus.getText().toString())) {
				matchStatus.setText("直播中");
			}

			// 写入本机缓存数据（XML）
			LiveTools.writeFile(context, matchId + ".xml".toString(), buildXml(liveScoreList));

		}
		// NetActivity.this.setTitle("加载了  " + values[0] + "%");

	}

	// 此方法在主线程执行，任务执行的结果作为此方法的参数返回。
	@Override
	protected void onPostExecute(String result) {
		if (refresh) {
			Log.i("PageTask", "onPostExecute()  " + Thread.currentThread().getId());
			proDialog.dismiss();
		}
	}

	private List<Map<String, Object>> getMatchDetail(String url) {
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		HttpClient client = new DefaultHttpClient();
		// 提拱默认的HttpClient实现
		HttpPost request;
		try {
			request = new HttpPost(new URI(url));
			request.addHeader("Accept-Encoding", "gzip");
			HttpResponse response = client.execute(request);
			// 判断请求是否成功
			if (response.getStatusLine().getStatusCode() == 200) { // 200表示请求成功
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String out = null;
					InputStream is = entity.getContent();
					if (entity.getContentEncoding().getValue().contains("gzip")) {
						out = LiveTools.isToString(is);
					} else {
						out = EntityUtils.toString(entity);
					}
					try {
						String result = new JSONObject(out).getString("result");
						if (Constant.Y.equals(result)) {
							JSONArray matches = new JSONObject(out).getJSONArray("results");

							for (int i = 0; i < matches.length(); i++) {
								Map<String, Object> map = new HashMap<String, Object>();

								map.put("scoreId", (String) matches.getJSONObject(i).get("scoreId"));

								String scoreTime = (String) matches.getJSONObject(i).get("scoreTime");
								scoreTime = scoreTime.replaceAll("\\n", "\n");
								map.put("scoreTime", scoreTime);
								map.put("homeTeamScore", matches.getJSONObject(i).get("homeTeamScore"));
								map.put("homeTeamIssucc", matches.getJSONObject(i).get("homeTeamIssucc"));
								map.put("visitTeamScore", matches.getJSONObject(i).get("visitTeamScore"));
								map.put("visitTeamIssucc", matches.getJSONObject(i).get("visitTeamIssucc"));
								map.put("scoreAction", matches.getJSONObject(i).get("scoreAction"));

								data.add(map);
							}
						} else {

						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return data;
	}

	private String buildXml(List<Map<String, Object>> liveScoreList) {
		XmlSerializer serializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();
		try {
			serializer.setOutput(writer);

			// <?xml version="1.0″ encoding="UTF-8″ standalone="yes"?>
			serializer.startDocument("UTF-8", true);
			// <liveScore number="1″>
			serializer.startTag(null, "liveScore");
			serializer.attribute(null, "matchId", matchId);
			for (int i = 0; i < liveScoreList.size(); i++) {
				Map<String, Object> liveScore = liveScoreList.get(i);

				// <detail>
				serializer.startTag(null, "detail");

				// <scoreId>
				serializer.startTag(null, "scoreId");
				serializer.text(String.valueOf(liveScore.get("scoreId")));
				serializer.endTag(null, "scoreId");
				// <matchId>
				serializer.startTag(null, "matchId");
				serializer.text(matchId);
				serializer.endTag(null, "matchId");
				// <scoreId>
				serializer.startTag(null, "homeTeamScore");
				serializer.text(String.valueOf(liveScore.get("homeTeamScore")));
				serializer.endTag(null, "homeTeamScore");
				// <scoreId>
				serializer.startTag(null, "homeTeamIssucc");
				serializer.text(String.valueOf(liveScore.get("homeTeamIssucc")));
				serializer.endTag(null, "homeTeamIssucc");
				// <scoreId>
				serializer.startTag(null, "visitTeamScore");
				serializer.text(String.valueOf(liveScore.get("visitTeamScore")));
				serializer.endTag(null, "visitTeamScore");
				// <scoreId>
				serializer.startTag(null, "visitTeamIssucc");
				serializer.text(String.valueOf(liveScore.get("visitTeamIssucc")));
				serializer.endTag(null, "visitTeamIssucc");
				// <scoreId>
				serializer.startTag(null, "scoreTime");
				serializer.text(String.valueOf(liveScore.get("scoreTime")));
				serializer.endTag(null, "scoreTime");
				// <scoreId>
				serializer.startTag(null, "scoreAction");
				serializer.text(String.valueOf(liveScore.get("scoreAction")));
				serializer.endTag(null, "scoreAction");

				serializer.endTag(null, "detail");
			}
			serializer.endTag(null, "liveScore");
			serializer.endDocument();

			return writer.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}